package com.lw.leetcode.arr.b;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/24 9:25
 */
public class EatenApples {

    public static void main(String[] args) {
        EatenApples test = new EatenApples();
        //  7
//        int[] arr1 = {1, 2, 3, 5, 2};
//        int[] arr2 = {3, 2, 1, 4, 2};
        // 5
        int[] arr1 = {3,0,0,0,0,2};
        int[] arr2 = {3,0,0,0,0,2};
        int i = test.eatenApples(arr1, arr2);

        System.out.println(i);
    }


    public int eatenApples(int[] apples, int[] days) {
        int len = 0;
        int length = days.length;
        for (int i = 0; i < length; i++) {
            len = Math.max(len, i + days[i]);
        }
        int[] arr = new int[len + 1];
        PriorityQueue<Integer> query = new PriorityQueue<>();
        int count = 0;
        int a = apples[0];
        if (a != 0) {
            a--;
            arr[0] = a ;
            count++;
            arr[days[0]] = -a ;
            if (a != 0) {
                query.add(days[0]);
            }
        }

        for (int i = 1; i < length; i++) {
            int c = apples[i];
            arr[i] = arr[i - 1] + arr[i] + c;
            arr[i + days[i]] -= c;
            if (c != 0) {
                query.add(i + days[i]);
            }
            while (!query.isEmpty() && query.peek() == i) {
                query.poll();
            }
            if (arr[i] > 0) {
                arr[i]--;
                count++;
                int p = query.peek();
                arr[p]++;
                if (arr[p] == 0) {
                    query.poll();
                }
            }
        }
        for (int i = length; i <= len; i++) {
            arr[i] = arr[i - 1] + arr[i];
            while (!query.isEmpty() && query.peek() == i) {
                query.poll();
            }
            if (arr[i] > 0) {
                arr[i]--;
                count++;
                int p = query.peek();
                arr[p]++;
                if (arr[p] == 0) {
                    query.poll();
                }
            }
        }
        return count;
    }

}
